package com.lyhengtongwl.zqsnews.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.base.BaseActivity;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.entity.NewsKsEntity;
import com.lyhengtongwl.zqsnews.entity.WecLoginBo;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.utils.AppConfig;
import com.lyhengtongwl.zqsnews.utils.DataCheckUtils;
import com.lyhengtongwl.zqsnews.utils.JpushSetAliasUtils;
import com.lyhengtongwl.zqsnews.utils.NewsToastUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.utils.TitleBuilder;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;
import com.lyhengtongwl.zqsnews.widget.CountTimer;


import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

public class NewsBindMobileActivity extends BaseActivity {
    @BindView(R.id.et_phone)
    EditText etPhone;//手机号
    @BindView(R.id.et_phoneCode)
    EditText et_phoneCode;//验证码
    @BindView(R.id.tv_done)//完成绑定
            TextView tv_done;
    @BindView(R.id.ed_referralCode)//推介人代码
            EditText ed_referralCode;
    @BindView(R.id.tv_getcode)
    TextView tv_getcode;

    private String nickName;
    private String headImgUrl;
    private String openId;
    private String sex;
    private String unionid;
    private CountTimer countTimer;
    private String codeid;

    private String mac;
    private String imei;
    private String androidId;
    private String lastUnique;

    @OnClick({R.id.tv_done, R.id.tv_getcode, R.id.tv_user, R.id.tv_privacy})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_done: //进行绑定手机号
                bindPhone();
                break;
            case R.id.tv_getcode://获取验证码
                if (!DataCheckUtils.isCellphone(etPhone.getText().toString().trim())) {
                    NewsToastUtils.showToast(NewsBindMobileActivity.this, "请输入正确的手机号！");
                    return;
                } else {
                    //发送验证码
                    sendVerify();
                }
                break;
            case R.id.tv_user://用户协议
                startActivity(new Intent(NewsBindMobileActivity.this, NewsWebCommonActivity.class).putExtra("url", AppConfig.getInstance(App.getContext()).get("userUrl")));
                break;
            case R.id.tv_privacy://隐私协议
                startActivity(new Intent(NewsBindMobileActivity.this, NewsWebCommonActivity.class).putExtra("url", AppConfig.getInstance(App.getContext()).get("privacyUrl")));
                break;
        }
    }

    /**
     * 隐藏软键盘(只适用于Activity，不适用于Fragment)
     */
    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 获取验证码
     */
    private void sendVerify() {
        countTimer.start();
        String mobile = etPhone.getText().toString();
        Task.getApiService().getPhoneCode(mobile).enqueue(new MyCallback<NewsBaseEntity>(NewsBindMobileActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                if ("1".equals(response.body().getCode())) {
                    NewsToastUtils.showToast(NewsBindMobileActivity.this, "验证码：" + response.body().getMsg());
                    String jsonStr = JSONObject.toJSONString(response.body().getData());
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    codeid = jsonObject.getString("codeid");
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countTimer != null) {
            countTimer.cancel();
            tv_getcode.setEnabled(true);
            tv_getcode.setText("获取验证码");
        }
    }

    @Override
    public void setListen() {
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBindStatus();
            }
        });
        et_phoneCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setBindStatus();
            }
        });
    }

    private void setBindStatus() {
        String myPhone = etPhone.getText().toString();
        String mphoneCode = et_phoneCode.getText().toString();
        if (TextUtils.isEmpty(myPhone) || TextUtils.isEmpty(mphoneCode)) {
            tv_done.setEnabled(false);
        } else {
            tv_done.setEnabled(true);
        }
    }

    @Override
    public void setTitleBarColor() {
        new TitleBuilder(this).setTitleText("")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_news_bind;
    }

    @Override
    public void initView() {
        countTimer = new CountTimer(tv_getcode);
        etPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)}); //限制输入位数
        et_phoneCode.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)}); //限制输入位数
    }

    @Override
    public void initData() {
        nickName = getIntent().getStringExtra("nickname");
        headImgUrl = getIntent().getStringExtra("avatar");
        openId = getIntent().getStringExtra("openid");
        sex = getIntent().getStringExtra("sex");
        unionid = getIntent().getStringExtra("unionId");
        //获取设备唯一标识之后注册成功上传设备信息
        mac = SPUtils.get(App.getContext(), "uniqueIdentifier", "") + "";
        imei = SPUtils.get(App.getContext(), "imei", "") + "";
        androidId = SPUtils.get(App.getContext(), "androidId", "") + "";
        lastUnique = SPUtils.get(App.getContext(), "lastUnique", "") + "";
    }

    private void bindPhone() {
        Dialog dialog = new CenterDialog(R.layout.loading_layout, NewsBindMobileActivity.this).showLoad("正在进行注册...");
        hideSoftKeyboard(NewsBindMobileActivity.this);
        if (DataCheckUtils.isCellphone(etPhone.getText().toString())) {
            WecLoginBo wecLoginBo = new WecLoginBo();
            wecLoginBo.setAppid(SPUtils.get(App.getContext(), "uniqueIdentifier", "00:00:00:02") + "");
            wecLoginBo.setAvatar(headImgUrl);
            wecLoginBo.setMobile(etPhone.getText().toString());
            wecLoginBo.setNickname(nickName);
            wecLoginBo.setOpenid(openId);
            wecLoginBo.setCode(et_phoneCode.getText().toString());
            wecLoginBo.setShareCode("");
            wecLoginBo.setSex(sex);
            wecLoginBo.setUnionid(unionid);
            wecLoginBo.setCodeid(codeid);
            Task.getApiService().bindPhone(wecLoginBo).enqueue(new MyCallback<NewsBaseEntity>(NewsBindMobileActivity.this) {
                @Override
                protected void onSuccess(Response<NewsBaseEntity> response) {
                    dialog.dismiss();
                    if ("1".equals(response.body().getCode())) {
                        String jsonStr = JSONObject.toJSONString(response.body().getData());
                        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                        String redBag = jsonObject.getInteger("redBag") + "";
                        SPUtils.put(App.getContext(), "redBag", redBag);
                        String token = jsonObject.getString("token");
                        Integer userId = jsonObject.getInteger("userId");
                        SPUtils.put(App.getContext(), "token", token);
                        SPUtils.put(App.getContext(), "userId", userId.toString());
                        String randomCode = jsonObject.getString("randomCode");
                        SPUtils.put(App.getContext(), "random_code", randomCode);
                        String shareCode = jsonObject.getString("shareCode");
                        SPUtils.put(App.getContext(), "shareCode", shareCode);
                        startActivity(new Intent(NewsBindMobileActivity.this, MainActivity.class));
                        new JpushSetAliasUtils(NewsBindMobileActivity.this).setAlias(userId + "");
                        upLoadUnique();
                        finish();
                    } else {
                        NewsToastUtils.showToast(NewsBindMobileActivity.this, response.body().getMsg());
                    }
                }

                @Override
                protected void onFailure(Throwable t) {
                    dialog.dismiss();
                    NewsToastUtils.showToast(NewsBindMobileActivity.this, "网络请求超时！");
                }
            });
        } else {
            NewsToastUtils.showToast(NewsBindMobileActivity.this, "手机号不正确！");
        }
    }

    @Override
    protected boolean isStatusBarBlack() {
        return true;
    }

//     注册成功之后进行提交 唯一标识
    private void upLoadUnique(){
        NewsKsEntity newsKsEntity=new NewsKsEntity();
        newsKsEntity.setMac(mac);
        newsKsEntity.setAndroidid3(androidId);
        newsKsEntity.setImei3(imei);
        newsKsEntity.setExtend1(lastUnique);
        Task.getApiService().upLoadUnique(newsKsEntity).enqueue(new MyCallback<NewsBaseEntity>(NewsBindMobileActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {

            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }
}
